#ifndef COMMON_H
#define COMMON_H

#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>

// 常量定义
const int DEFAULT_PORT = 8888;
const int BUFFER_SIZE = 1024;
const int MAX_CLIENTS = 100;

// 消息类型
enum MessageType {
    MSG_LOGIN = 1,
    MSG_LOGOUT = 2,
    MSG_CHAT = 3,
    MSG_USER_LIST = 4,
    MSG_ERROR = 5
};

// 消息结构
struct Message {
    MessageType type;
    std::string username;
    std::string content;
    
    Message() : type(MSG_CHAT) {}
    Message(MessageType t, const std::string& user, const std::string& msg) 
        : type(t), username(user), content(msg) {}
    
    // 序列化消息为字符串
    std::string serialize() const {
        return std::to_string(static_cast<int>(type)) + "|" + username + "|" + content;
    }
    
    // 从字符串反序列化消息
    static Message deserialize(const std::string& data) {
        Message msg;
        size_t pos1 = data.find('|');
        size_t pos2 = data.find('|', pos1 + 1);
        
        if (pos1 != std::string::npos && pos2 != std::string::npos) {
            msg.type = static_cast<MessageType>(std::stoi(data.substr(0, pos1)));
            msg.username = data.substr(pos1 + 1, pos2 - pos1 - 1);
            msg.content = data.substr(pos2 + 1);
        }
        return msg;
    }
};

// 客户端信息结构
struct ClientInfo {
    int socket;
    std::string username;
    std::string ip;
    
    ClientInfo(int sock, const std::string& user, const std::string& addr) 
        : socket(sock), username(user), ip(addr) {}
};

// 工具函数
inline std::string getCurrentTime() {
    time_t now = time(0);
    char* timeStr = ctime(&now);
    std::string result(timeStr);
    if (!result.empty() && result.back() == '\n') {
        result.pop_back();
    }
    return result;
}

inline void printLog(const std::string& message) {
    std::cout << "[" << getCurrentTime() << "] " << message << std::endl;
}

struct PrivateChat {
    std::string chatId;           // 聊天ID (user1_user2)
    std::string user1;            // 参与者1
    std::string user2;            // 参与者2
    time_t createTime;            // 创建时间
    time_t lastMessageTime;      // 最后消息时间
};

struct PrivateMessage {
    std::string messageId;        // 消息ID
    std::string chatId;          // 所属对话
    std::string fromUser;        // 发送者
    std::string toUser;          // 接收者
    std::string content;         // 消息内容
    time_t timestamp;            // 时间戳
    bool isRead;                 // 是否已读
};

#endif // COMMON_H 